package com.ji.TestZookeeper.listener;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.utils.ZKPaths;

import com.ji.TestZookeeper.curator.ClientFactory;

public class CuratorWatch {

	public static void main(String[] args) throws Exception {
		CuratorFramework client = ClientFactory.newClient();
		client.start();
		nodewatch(client);
		valueWatch(client);
		System.out.println("监听开始/zk........");
		Thread.sleep(Long.MAX_VALUE);
	}

	/**
	 * 
	 * 监听节点变化
	 * 
	 */
	public static void nodewatch(CuratorFramework client) throws Exception {
		PathChildrenCache cache = new PathChildrenCache(client, "/testWatch", false);
		cache.start();
		PathChildrenCacheListener plis = new PathChildrenCacheListener() {
			@Override
			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
				switch (event.getType()) {
				case CHILD_ADDED: {
					System.out.println("Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
					break;
				}

				case CHILD_UPDATED: {
					System.out.println("Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
					break;
				}

				case CHILD_REMOVED: {
					System.out.println("Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
					break;
				}

				default:
					System.out.println("Note default");
				}

			}
		};
		// 注册监听
		cache.getListenable().addListener(plis);
		// cache.close();
	}

	public static void valueWatch(CuratorFramework client) throws Exception {
		final NodeCache cache = new NodeCache(client, "/testWatch");
		cache.start();
		NodeCacheListener lis = new NodeCacheListener() {
			@Override
			public void nodeChanged() throws Exception {
				System.out.println("NodeCache changed, data is: " + new String(cache.getCurrentData().getData()));
			}
		};
		cache.getListenable().addListener(lis);
	}

}